package com.iussoft.receiveData.controller;

import java.io.*;
import java.nio.charset.Charset;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import com.apache.tools.NumberUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.StreamUtils;

/**
 * @description: 覆盖HttpServletRequestWrapper类getReader()和getInputStream()方法
 * @author: Hou Dayu
 * @date: Created in 2020/10/21
 */
public class MAPIHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    public MAPIHttpServletRequestWrapper(HttpServletRequest request)
            throws IOException {
        super(request);
//        String bodyString = StreamUtils.copyToString(request.getInputStream(), Charset.forName("UTF-8"));
//        body = bodyString.getBytes("UTF-8");
        DataInputStream dis = new DataInputStream(request.getInputStream());
        ByteArrayOutputStream baot = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024]; //定义一个数组 用来读取
        int n = 0;//每次读取输入流的量
        while((n=dis.read(bytes))!=-1){
            baot.write(bytes);  //将读取的字节流写入字节输出流
        }
        body = baot.toByteArray();//将字节输出流转为自己数组。
    }

    public String fileSize(){
        double size = NumberUtils.divide(body.length, 1024, 4);
        if(size > 1024){
            return (size/1024)+"M";
        }
        return size+"KB";
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return bais.read();
            }
            @Override
            public boolean isFinished() {
                return false;
            }
            @Override
            public boolean isReady() {
                return false;
            }
            @Override
            public void setReadListener(ReadListener readListener) {
            }
        };
    }
}
